package com.quanshu.exchange.ui.gui.profile.order_fragment;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.ShopInterface;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.entity.MyOrderEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.BaseFragment;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;
import com.quanshu.exchange.ui.gui.profile.AllOrderActivity;
import com.quanshu.exchange.ui.gui.web_page.OrderPaymentActivity;
import com.quanshu.shop.base.tool.BaseTool;
import com.quanshu.shop.order.view.OrderDetailsActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;

/**
 * 待付款
 * Created by xiniu003 on 2018/1/12.
 */

public class NonPaymentFragment extends BaseFragment {

    private static BaseActivity mContext;

    @BindView(R.id.my_order_null)
    LinearLayout myOrderNull;
    @BindView(R.id.order_recy)
    RecyclerView orderRecy;

    private List<MyOrderEntity> datas;//全部数据
    private SingleAdapter<MyOrderEntity> adapter;

    public static NonPaymentFragment newInstance(BaseActivity context) {
        NonPaymentFragment f = new NonPaymentFragment();
        Bundle args = new Bundle();
        mContext = context;
        f.setArguments(args);
        return f;
    }

    @Override
    public int setFragmentLayoutID() {
        return R.layout.fragment_order_all;
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

        orderRecy.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new SingleAdapter<>(new DataDisplayer<MyOrderEntity>(getActivity(), R.layout.item_order) {
            @Override
            public void bindData(BaseViewHolder holder,
                                 LayoutWrapper<MyOrderEntity> wrapper,
                                 MyOrderEntity item,
                                 int position) {

                holder.setText(R.id.order_number, "订单号：" + item.getOrder_no());
                holder.setText(R.id.order_type, item.getOrderStatuText());
                holder.setImageUrl(R.id.order_shop_image,
                        Config.URL_HOST_SHOP + item.getImg(),
                        R.drawable.default_avatar);
                holder.setText(R.id.order_shop_price_pianyi, item.getGoods_price());
                // niujifen
                if (item.getPayment_options() == 1) {
                    holder.setImage(R.id.pay_flag, R.drawable.icon_njf_2_0);
                    holder.setImage(R.id.pay_flag_1, R.drawable.icon_njf_2_0);
                } else {
                    holder.setImage(R.id.pay_flag, R.drawable.icon_rmb_2_0);
                    holder.setImage(R.id.pay_flag_1, R.drawable.icon_rmb_2_0);
                }
                holder.setText(R.id.order_shop_price_gui, item.getSum_price());
                TextView guiPriceR = holder.getView(R.id.order_shop_price_gui);
                guiPriceR.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                holder.setText(R.id.order_shop_number, "x" + item.getGoods_nums());

                holder.setText(R.id.order_shop_name, item.getGoods_name());

                String goodsArray = item.getGoods_array();
                try {
                    JSONObject jsonObject = new JSONObject(goodsArray);
                    holder.setText(R.id.order_shop_serial_number, jsonObject.getString("goodsno"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                holder.setText(R.id.order_shop_price, item.getGoods_price());

                TextView payBtn = holder.getView(R.id.edit_order_one);
                TextView deleteBtn = holder.getView(R.id.edit_order_two);
                TextView applyRefund = holder.getView(R.id.tv_order_apply_refund);
                TextView refunding = holder.getView(R.id.tv_order_refunding);
                payBtn.setVisibility(View.VISIBLE);
                deleteBtn.setVisibility(View.VISIBLE);
                applyRefund.setVisibility(View.GONE);
                refunding.setVisibility(View.GONE);

                if (item.getOrderStatuText().equals("待付款")) {

                    payBtn.setText("付款");
                    deleteBtn.setText("取消订单");

                    holder.setOnClickListener(R.id.edit_order_one, view -> {
                        Intent intent = new Intent(getActivity(), OrderPaymentActivity.class);
                        intent.putExtra("myOrderEntity", item);
                        startActivity(intent);
                    });

                    holder.setOnClickListener(R.id.edit_order_two, view -> {
                        doCancelOrder(position,item);//取消订单
                    });

                }
                //订单详情
                holder.setOnClickListener(R.id.item_order_llt, view -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(AllOrderActivity.ORDER_ID, item.getId());
                    BaseTool.goActivity(getActivity(), OrderDetailsActivity.class, bundle);
//                    Intent intent = new Intent(getActivity(), OrderDetailsActivity.class);
//                    intent.putExtra("orderId", item.getId());
//                    intent.putExtra("myOrderEntity", item);
//                    startActivity(intent);
                });
            }
        });

        orderRecy.setAdapter(adapter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        return rootView;
    }

    //取消订单
    private void doCancelOrder(int position,MyOrderEntity item) {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .doCancelOrder(AppUtils.getSignParams(datas.get(position).getId(), "cancel"), datas.get(position).getId(), "cancel",item.getGoods_type())
                .compose(new BaseTransformer<>((BaseActivity) getActivity()))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        datas.remove(position);
                        adapter.setData(datas);
                    }
                });

    }

    //全部订单
    private void getOrderList() {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .getOrderList(AppUtils.getSignParams(String.valueOf(MyApplication.getInstance().getCurrentUser().getId())),
                        String.valueOf(MyApplication.getInstance().getCurrentUser().getId()), 2)
                .compose(new BaseTransformer<>(mContext))
                .subscribe(new BaseObserver<BaseResponse<List<MyOrderEntity>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<MyOrderEntity>> response) {
                        if (response.getData() != null) {
                            datas = response.getData();
                            adapter.setData(datas);
                            if (myOrderNull != null) {
                                myOrderNull.setVisibility(View.GONE);
                            }
                        } else {
                            if (myOrderNull != null) {
                                myOrderNull.setVisibility(View.VISIBLE);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                    }
                });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            getOrderList();
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        getOrderList();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

}
